package com.zbkj.common.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.zbkj.common.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

/**
 * @Auther:
 * @Date: 2024/7/7 21:15
 * @Description:
 */
@Slf4j
@Component
public class OssClientUtil {

    @Autowired
    private OSS ossClient;
    @Autowired
    private OSSProperties ossProperties;

    public String upload(String path, InputStream in) {
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBacketname(), path, in);
            // 上传文件。
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            log.info("ossupload-file:{}-end:",path,putObjectResult.getETag());
            return String.format("%s/%s",ossProperties.getDomain(),path);
        } catch (Exception e){
            log.error("ossupload-file:{}--error:",path,e);
            throw new CommonException("文件上传oss异常");
        }
    }

    public String upload(String path, File file) {
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBacketname(), path, file);
            // 上传文件。
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            log.info("ossupload-file:{}-end:",path,putObjectResult.getETag());
            return String.format("%s/%s",ossProperties.getDomain(),path);
        } catch (Exception e){
            log.error("ossupload-file:{}--error:",path,e);
            throw new CommonException("文件上传oss异常");
        }
    }

    public String clearDomain(String path) {
        if(StringUtils.isBlank(path)){
            return path;
        }
        String domainPath = ossProperties.getDomain()+"/";
        if(path.contains(domainPath)){
            return path.replace( domainPath, "");
        }
        return path;
    }

    public String addDomain(String path) {
        if(StringUtils.isBlank(path)){
            return path;
        }
        String pathLow = path.toLowerCase();
        if(pathLow.startsWith("http://") || pathLow.startsWith("https://")) {
            return path;
        }
        return String.format("%s/%s", ossProperties.getDomain(),path);
    }

    public String addInnerDomain(String path) {
        if(StringUtils.isBlank(path)){
            return path;
        }
        String pathLow = path.toLowerCase();
        if(pathLow.startsWith("http://") || pathLow.startsWith("https://")) {
            return path;
        }
        return String.format("%s/%s", ossProperties.getInnerDomain(),path);
    }
}
